# -*- coding: UTF-8 -*-
# cython: language_level=3
import base64

import chardet


def auto_decode(b):
    try:
        result = str(b, encoding="utf-8")
    except:
        try:
            result = str(b, encoding="gbk")
        except:
            result = str(b, encoding=chardet.detect(b)['encoding'])
    return result


def get_qq_url(src_url):
    real_url = auto_decode(base64.b64decode(src_url[7:]))
    # print('qq转真实链接: ', real_url[:100])
    return real_url


def get_thunder_url(url):
    if url.startswith('thunder://') or url.startswith('Thunder://'):
        mystr = url[10:]
    else:
        mystr = url
    mystr = bytes(mystr, encoding="utf8")
    missing_padding = 4 - len(url) % 4
    if missing_padding:
        mystr += b'=' * missing_padding
    mystr2 = base64.decodebytes(mystr)
    result = auto_decode(mystr2)
    return result[2:-2]


def get_flash_get(src_url):
    tmp_url = base64.b64decode(src_url[11:])[10:- 10]
    real_url = auto_decode(tmp_url)
    # print('flashget转真实链接: ', real_url[:100])
    return real_url


def download_url_transform(src_url):
    myurl = src_url.lower()
    if myurl.startswith('thunder://'):
        return get_thunder_url(src_url)
    elif myurl.startswith('qqdl://'):
        return get_qq_url(src_url)
    elif myurl.startswith('flashget://'):
        return get_flash_get(src_url)
    else:
        print('链接不在转换范围内')


if __name__ == '__main__':
    print(download_url_transform('Thunder://QUFodHRwOi8vaW0uYmFpZHUuY29tL2luc3RhbGwvQmFpZHVIaS5leGVaWg=='))
    print(download_url_transform(
        'thunder://QUFodHRwOi8vb2t4eHh4enkueHpva3p5enkuY29tLzIwMTkxMDA0LzE5MzkyX2NjYTdjNzIyL+S4reWbveacuumVvy1IQy5tcDRaWg=='))
    # download_url_transform('qqdl://aHR0cDovL2ltLmJhaWR1LmNvbS9pbnN0YWxsL0JhaWR1SGkuZXhl')

    print(download_url_transform(
        'thunder://QUFodHRwOi8vb2t6eS54em9renl6eS5jb20vMjAyMDAyMDkvMTcwODBfMzE0MGEyNmUv0rbOyjTUwdPvLm1wNFpa'))
    print(download_url_transform(
        'Thunder://QUFmdHA6Ly81OjVAZDMuZGwxMjM0LmNvbToyNTM5L1vnlLXlvbHlpKnloIJ3d3cuZHkyMDE4LmNvbV3lpoLmnpzmnInojYbmo5hCROS4reiLseWPjOWtly5hdmlaWg'))

    '[thunder|Thunder|Flashget|flashget|qqdl]://[0-9a-zA-Z=]+'
    print(download_url_transform(
        'Thunder://QUFmdHA6Ly9hOmFAZHguZGwxMjM0LmNvbTo1MTA5L1u159OwzOzMw3d3dy5keTIwMTguY29tXcCvscrQodDCvvbSu8qkuLpCRLn6yNXLq9Pv1tDX1i5ta3ZaWg'))
